package com.atguigu.delivery.service.impl;

import com.atguigu.delivery.dao.api.CompanyDao;
import com.atguigu.delivery.dao.api.DeliveryDao;
import com.atguigu.delivery.dao.impl.CompanyDaoImpl;
import com.atguigu.delivery.dao.impl.DeliveryDaoImpl;
import com.atguigu.delivery.entity.Company;
import com.atguigu.delivery.entity.Delivery;
import com.atguigu.delivery.service.api.DeliveryService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class DeliveryServiceImpl implements DeliveryService {

    private DeliveryDao deliveryDao = new DeliveryDaoImpl();
    private CompanyDao companyDao = new CompanyDaoImpl();

    @Override
    public List<Delivery> getDeliveryListByUserId(Integer userId) {

        // 1、查询 Delivery 数据集合
        List<Delivery> deliveryList = deliveryDao.selectDeliveryListByUserId(userId);

        // 2、为了给 Delivery 装配 Company，查询 Company 数据
//        for (Delivery delivery : deliveryList) {
//            int companyId = delivery.getCompanyId();
//            // 性能上，典型的耗时的操作：
//            // A、I/O 操作
//            // B、数据库操作
//            // C、访问网络的操作
//            Company company = companyDao.selectCompanyById(companyId);
//            delivery.setCompany(company);
//        }
        // 循环 10 次，每次从数据库查询一条记录：为了点 10 个菜，在外卖平台下单 10 次，路上要往返 10 次
        // 一次性从数据库查询 10 条记录：下单一次点 10 个菜，路上只往返一次
        List<Company> companyList = companyDao.selectAll();

        // 3、把 companyList 转为 Map 集合
        Map<Integer, Company> companyMap =
                companyList
                        .stream()
                        .collect(Collectors.toMap(company -> company.getId(), company -> company));

        // 4、借助 companyMap 为 deliveryList 中每一个对象组装 Company
        deliveryList.forEach(delivery -> delivery.setCompany(companyMap.get(delivery.getCompanyId())));

        return deliveryList;
    }

    @Override
    public void removeDeliveryById(String id) {
        deliveryDao.deleteDeliveryById(id);
    }

    @Override
    public void saveDelivery(Delivery delivery) {
        deliveryDao.insertDelivery(delivery);
    }

    @Override
    public Delivery getDeliveryById(String id) {
        return deliveryDao.selectDeliveryById(id);
    }

    @Override
    public void updateDelivery(Delivery delivery) {
        deliveryDao.updateDelivery(delivery);
    }
}
